package cn.dinkevin.xui.util;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import cn.dinkevin.xui.XUI;
import cn.dinkevin.xui.thread.ThreadExecutor;

/**
 * 设备相关工具类</br>
 * Created by ChengPengFei on 2016/10/30 0030.</br>
 */

public final class DeviceUtil {

    private static String g_deviceInfo;

    /**
     * 计算设备唯一码
     * @return 32位字母
     */
    public static String getUniqueCode(){
        if(TextUtils.isEmpty(g_deviceInfo)){
            String deviceInfo = readDeviceInfo();
            g_deviceInfo = MD5Util.calculate(deviceInfo);
        }
        return g_deviceInfo;
    }

    /**
     * 读取设备信息
     * @return
     */
    private static String readDeviceInfo(){

        StringBuffer buffer = new StringBuffer();
        Context context = XUI.getInstance().getContext();
        if(null == context){
            LogUtil.e("ThreadExecutor need register");
        }

        // 尝试读取 MAC 地址
        try{
            WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
            // 确认 Wifi 打开状态
            if(!wifiManager.isWifiEnabled()){
                wifiManager.setWifiEnabled(true);
            }

            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            if(null == wifiInfo || TextUtils.isEmpty(wifiInfo.getMacAddress())){
                return buffer.toString();
            }
            buffer.append("wifi:");
            buffer.append(wifiInfo.getMacAddress());
        }catch (Exception e){
            LogUtil.e("readDeviceInfo, getEntity wifi mac",e.getMessage());
        }

        // 尝试读取 IMEI
        try{
            TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
            String imei = telephonyManager.getDeviceId();
            buffer.append(TextUtils.isEmpty(imei) ? "" : "imei:"+imei);

            String serialNumber = telephonyManager.getSimSerialNumber();
            buffer.append(TextUtils.isEmpty(serialNumber) ? "" : "sn:"+serialNumber);
        }catch (Exception e){
            LogUtil.e("make unique code, getEntity imei",e.getMessage());
        }

        // 尝试读取蓝牙地址
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(null != bluetoothAdapter){
            String bluetoothAddress = bluetoothAdapter.getAddress();
            buffer.append("bt:");
            buffer.append(bluetoothAddress);
        }

        // 获取系统首次启动时生成的 android_id
        String androidId = Settings.System.getString(context.getContentResolver(), Settings.System.ANDROID_ID);
        buffer.append(TextUtils.isEmpty(androidId) ? "":"id:" + androidId);

        // 读取设备品牌、基板名称、设备制造商、设备驱动名称
        buffer.append("brand:" + Build.BRAND);
        buffer.append("board:" + Build.BOARD);
        buffer.append("device:" + Build.DEVICE);
        return buffer.toString();
    }


    /**
     * 比较版本号的大小,前者大则返回一个正数,后者大返回一个负数,相等则返回0
     * @link http://blog.csdn.net/sowhat_ah/article/details/43955337
     * @param version1
     * @param version2
     * @return
     */
    public static int compareVersion(String version1, String version2) throws Exception {
        if (version1 == null || version2 == null) {
            throw new Exception("compareVersion error:illegal params.");
        }
        String[] versionArray1 = version1.split("\\.");//注意此处为正则匹配，不能用"."；
        String[] versionArray2 = version2.split("\\.");
        int idx = 0;
        int minLength = Math.min(versionArray1.length, versionArray2.length);//取最小长度值
        int diff = 0;
        while (idx < minLength
                && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0//先比较长度
                && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {//再比较字符
            ++idx;
        }
        //如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大；
        diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
        return diff;
    }

    /**
     * 设备描述信息</br>
     * 格式如下：</br>
     * 操作系统，系统版本，品牌 型号，软件版本
     * @return
     */
    public static String getDescription(){
        String description = "Android ";
        description += Build.VERSION.RELEASE;
        description += ",";
        description += Build.MANUFACTURER;
        description += " ";
        description += Build.MODEL;
        description += ",";
        description += getVersionName();
        return description;
    }

    /**
     * 操作系统版本
     * @return
     */
    public static String getOSVersion(){
        return Build.VERSION.RELEASE;
    }

    /**
     * 机型
     * @return
     */
    public static String getPhoneModel(){
        return Build.MANUFACTURER + " " + Build.MODEL;
    }

    /**
     * 应用版本名
     * @return
     */
    public static String getVersionName(){
        try{
            return XUI.getInstance().getContext().getPackageManager().getPackageInfo(XUI.getInstance().getContext().getPackageName(),0).versionName;
        }catch (Exception e){
            LogUtil.e("getEntity version name",e.getMessage());
        }
        return "";
    }

    /**
     * 应用版本号
     * @return
     */
    public static int getVersionCode(){
        try{
            return XUI.getInstance().getContext().getPackageManager().getPackageInfo(XUI.getInstance().getContext().getPackageName(),0).versionCode;
        }catch (Exception e){
            LogUtil.e("getEntity version name",e.getMessage());
        }
        return 0;
    }

    /**
     * 获取 Application 标签内部的 Metal-data 数据
     * @param metalDataKey
     * @return
     */
    public static String getMetaData(String metalDataKey){
        try {
            ApplicationInfo app = XUI.getInstance().getContext().getPackageManager().getApplicationInfo(XUI.getInstance().getContext().getPackageName(), PackageManager.GET_META_DATA);
            return app.metaData.getString(metalDataKey);
        }catch (Exception e){
            LogUtil.e("getApplicationInfo",e.getMessage());
        }
        return null;
    }

    /**
     * 获取应用程序的名字
     * @return
     */
    public static String getAppName(){
        try
        {
            PackageManager packageManager = XUI.getInstance().getContext().getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    XUI.getInstance().getContext().getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return XUI.getInstance().getContext().getResources().getString(labelRes);
        }
        catch (PackageManager.NameNotFoundException e) {
            LogUtil.e("getAppName",e.getMessage());
        }
        return null;
    }
}
